#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName  :down_ppt.py
# @Time      :2023/12/25 
# @Author    :CL
# @email     :1037654919@qq.com
# 下载ppt到本地
import random
import time
import requests
from retrying import retry

from utils import mongo_manager, get_proxy, proxies

islide_data = mongo_manager('islide_data', db='public_data')
@retry(stop_max_attempt_number=5, wait_fixed=5000)
def down_ppt(id='3508772'):
    headers = {
        "Accept": "*/*",
        "Accept-Language": "zh-CN,zh;q=0.9",
        "Access-Control-Request-Headers": "app-language,authorization,content-type,deviceid,source",
        "Access-Control-Request-Method": "GET",
        "Cache-Control": "no-cache",
        "Connection": "keep-alive",
        "Origin": "https://www.islide.cc",
        "Pragma": "no-cache",
        "Referer": "https://www.islide.cc/ppt/template/4884086.html",
        "Sec-Fetch-Dest": "empty",
        # "Authorization": "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VySW5mbyI6eyJhY2NvdW50SWQiOjY4MDY1NDAsImxvZ2luVHlwZSI6InBob25lIiwibmFtZSI6NTI5NDIzOX0sImlzcyI6Ik1JTkciLCJleHAiOjE3MDYwNjM4NTQsImlhdCI6MTcwMzQ3MTg1NH0.Tt4ch7XpWO3UQPvdj72bw_chtQMQwIOgNVjKVxKyyA4",
        "Authorization": "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VySW5mbyI6eyJhY2NvdW50SWQiOjY4MDY1NDAsImxvZ2luVHlwZSI6InBob25lIiwibmFtZSI6NTI5NDIzOX0sImlzcyI6Ik1JTkciLCJleHAiOjE3MTQwMTEzODksImlhdCI6MTcxMTQxOTM4OX0.tuqWm-6DTxl3t4D4igdplx9BYr1K6qtlEeYjQbjA-LQ",

        "Sec-Fetch-Mode": "cors",
        "Sec-Fetch-Site": "same-site",
        "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
    }
    url = f"https://store-api.islide.cc/web/resources/down/{id}"
    params = {
        "files": "default"
    }
    params = {
        "files": "16x9"
    }
    response = requests.get(url, headers=headers, params=params,timeout=10, proxies=proxies)
    # requests.session().close()
    print(response.url, response)
    print(response.text)
    if response.status_code == 200:
        return response.json()


def downdata():
    base_path = '/home/chenglei3/work/data/islide/'
    num = 50 # 每天能下载50个
    allnum = 1000 # 预留处理资源不存在的情况，因为暂时不清楚当返回资源不存在时，会不会消耗下载次数
    while num > 0 and allnum > 0:
        seed = islide_data.find_one_and_update({"type": "template", "status": None}, {"status": "doing"})
        reslut = down_ppt(id=seed['id'])
        if reslut.get('msg')=='资源不存在':
            islide_data.updateOne({"_id": seed['_id']}, {'status': 'nodata'})
        if reslut.get('msg') == '今日下载次数超限':
            break
        if reslut.get('msg')=='执行成功':
            num -= 1
            url = reslut.get('data')
            print(url)
            response = requests.get(url)
            file_name = str(url).split('?')[0].split('/')[-1]
            with open(base_path + file_name, 'wb') as f:
                f.write(response.content)
            islide_data.updateOne({"_id":seed['_id']},{'status':'done'})

        allnum -= 1
        time.sleep(random.randint(20,60))

if __name__ == "__main__":
    print()
    downdata()
    islide_data.close()
